<template>
  <div>
    <!-- <div v-for="(items,indexs) in arr" :key="indexs"> -->
    <el-dialog :title="title" v-model="open" width="80%" :before-close="cancel">
      <!-- class="dialog-wrap" align-center
      modal-class="modal-wrap" :modal="false" :close-on-click-modal="false" :lock-scroll="false" draggable -->
      <div style="display: flex;flex-wrap: wrap;">
        <div class="iframeBg" style="width: 430px;height: 774px;overflow-y: auto;">
          <iframe :src="`https://data.wtytl.com:9000/project_config/${project}.html?project=${project}`" frameborder="0"
            style="position: absolute;width: 384px;height: 690px;top: 65px;left: 23px;"></iframe>
        </div>
        <div style="flex: 1;margin-top: 15px;">
          <el-form ref="actionDialog" :model="form" :rules="rules" label-width="100px">
            <el-row :gutter="22">
              <el-col :span="22">
                <el-form-item label="命令" prop="deviceAction">
                  <!-- <el-select v-model="form.deviceAction" placeholder="请选择命令" clearable style="width:300px;">
                          <el-option v-for="(item,index) in device_action" :key="item.command" :label="item.label"
                            :value="item.value" />
                        </el-select> -->
                  <el-input v-model="form.deviceAction" clearable disabled placeholder="请选择命令" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="22">
                <el-form-item label="设备" prop="device">
                  <el-input type="textarea" :rows="4" v-model="form.device" placeholder="" />
                  <div style="display: block;width: 100%;" class="mt10">
                    <span style="font-weight: bold !important;">
                      已选择设备:
                    </span>
                    <span>
                      {{form.deviceName}}
                    </span>
                  </div>
                  <div class="mt10" style="display: block !important;">
                    <el-button type="primary" @click="handleSelectProject">选择项目</el-button>
                    <el-button type="primary" @click="handleDeviceGroup">选择分组</el-button>
                    <el-button type="primary" @click="handleDevice">选择设备</el-button>
                  </div>

                </el-form-item>
              </el-col>
              <el-col :span="22" class="mt10">
                <el-form-item label="参数内容" prop="content">
                  <!-- <el-input type="textarea" :rows="10" v-model="form.content" placeholder="" /> -->
                  <el-button type="primary" @click="handleCheckQuery">查询参数</el-button>
                  <div v-if="form.content" style="width: 100%;font-weight: 500;margin-top: 10px;margin-bottom: 10px;">
                    <span style="margin-right: 50px;">项目：{{project}}</span>
                    <span style="margin-right: 50px;">创建时间：{{form.createTime}}</span>
                    <span>更新时间：{{form.updateTime}}</span>
                  </div>
                  <div>
                    {{form.content}}
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog class="dialog-wrap2" :title="TwoTitle" align-center v-model="openTwo" width="800px"
      :before-close="cancelTwo">
      <div>
        <div class="mb10" style="display: flex;align-items: center;">
          <el-form label-width="100px">
            <el-form-item :label="TwoTitle == '选择项目' ? '项目名称' : TwoTitle == '选择设备分组' ? '设备分组名' : '设备名字' ">
              <el-input v-model="selectName" placeholder="" style="width: 300px;" clearable />
              <el-button type="primary" class="ml10" @click="handleSelectTable">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <Table ref="pageTableRef" :table-data="tableData" :border="true" size="small" :loading="loading"
          :columns="columns" :is-pagination="false" :selection="true" :show-index="true"
          @handleSelectionChange="handleSelectionChange">
          <!-- <template #isScriptRunning="scope">
            <el-tag v-if="scope.row.isScriptRunning" type="success">启动</el-tag>
            <el-tag v-else type="info">未启动</el-tag>
          </template> -->
        </Table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitSelect">确 定</el-button>
          <el-button @click="cancelTwo">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- </div> -->
  </div>
</template>

<script setup name="actionDialog">
  import { getSelectTypeList, updateDevices, getDevicesActionMessage, getConfigData } from "@/api/deviceManage/index.js";
  const { proxy } = getCurrentInstance();
  const emit = defineEmits(["cancel"]);
  const { device_action } = proxy.useDict('device_action'); // 设备操作
  const open = ref(false);
  const openTwo = ref(false);
  const title = ref("发送命令");
  const TwoTitle = ref("选择项目");
  const buttonLoading = ref(false);
  const tableData = ref([]);
  const loading = ref(false);
  const columns = ref([]);
  const project = ref('哔哩');
  const selectData = ref('');
  const selectName = ref('');
  const data = reactive({
    form: {
      deviceAction: '下发配置', // 命令
      device: '', // 设备
      deviceName: '',
      content: '', // 附加内容
      createTime: '',
      updateTime: '',
      selectDate: '',
    },
    queryParams: {
      pageNum: 1,
      pageSize: 100,
    },
    rules: {
      device: [
        { required: true, message: "请选择设备", trigger: "change" }
      ],
      content: [
        { required: true, message: "请输入附加内容", trigger: "blur" }
      ],
    }
  });
  const { queryParams, form, rules } = toRefs(data);
  function getCurrentDate() {
    var today = new Date();
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0'); // 注意月份从0开始
    var yyyy = today.getFullYear();
    return `${yyyy}-${mm}-${dd}`;
  }
  function submitSelect() {
    if (selectData.value.length) {
      // console.log(selectData.value, 'ABCDEFG-submitSelect');
      // console.log(selectData.value.length, 'ABCDEFG-submitSelect-length');
      // console.log(selectData.value.map(item => item.id), 'ABCDEFG-submitSelect-id');
      // console.log(selectData.value.map(item => item.name), 'ABCDEFG-submitSelect-name');
      form.value.device = selectData.value.map(item => item.id).join();
      form.value.deviceName = selectData.value.map(item => item.name).join();
      openTwo.value = false;
    } else {
      openTwo.value = false;
    }
    // form.value.device = selectData.value;
    // openTwo.value = false;
  }
  function handleSelectTable(row) {
    if (TwoTitle.value == '选择项目') {
      getSelectTypeList({
        type: 'project',
        project: project.value,
        selectDate: form.value.selectDate,
        name: selectName.value
      }).then(response => {
        if (response.length) {
          response.forEach(element => {
            if (element.deviceIdList && element.deviceIdList.length) {
              element.deviceIdString = element.deviceIdList.map(item => {
                return {
                  id: item.id,
                  name: item.name
                };
              });
            } else {
              element.deviceIdString = [];
            }
          });
        }
        // console.log(response, 'ABCDEFG-handleSelectProject');
        tableData.value = response || [];
      });
    }

    if (TwoTitle.value == '选择项目') {
      getSelectTypeList({
        type: 'deviceGroup',
        project: project.value,
        selectDate: form.value.selectDate,
        name: selectName.value
      }).then(response => {
        if (response.length) {
          response.forEach(element => {
            if (element.deviceIdList && element.deviceIdList.length) {
              element.deviceIdString = element.deviceIdList.map(item => {
                return {
                  id: item.id,
                  name: item.name
                };
              });
            } else {
              element.deviceIdString = [];
            }
          });
        }
        // console.log(response, 'ABCDEFG-handleSelectProject');
        tableData.value = response || [];
      });
    }
    if (TwoTitle.value == '选择设备') {
      if (selectName.value) {
        tableData.value = tableData.value.filter(item => item.name.toLowerCase().includes(selectName.value.toLowerCase()));
      } else {
        getSelectTypeList({
          type: 'project',
          project: project.value,
          selectDate: form.value.selectDate
        }).then(response => {
          tableData.value = response.deviceIdList || [];
          // console.log(response, 'handleDevice');
          if (response.length) {
            response.forEach(element => {
              if (element.name == project.value) {
                tableData.value = element.deviceIdList || [];
              }
            });
          }
        });
      }
    }
  }
  function handleSelectProject() {
    TwoTitle.value = '选择项目';
    columns.value = [
      {
        prop: 'name',
        label: '项目',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'userName',
        label: '所属',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
    ];
    getSelectTypeList({
      type: 'project',
      project: project.value,
      selectDate: form.value.selectDate
    }).then(response => {
      if (response.length) {
        response.forEach(element => {
          if (element.deviceIdList && element.deviceIdList.length) {
            element.deviceIdString = element.deviceIdList.map(item => {
              return {
                id: item.id,
                name: item.name
              };
            });
          } else {
            element.deviceIdString = [];
          }
        });
      }
      // console.log(response, 'ABCDEFG-handleSelectProject');
      tableData.value = response || [];
      openTwo.value = true;
    });
  }
  function handleCheckQuery() {
    getConfigData({
      project: project.value,
      userId: form.value.userId
    }).then(response => {
      // console.log(response, 'ABCDEFG-handleCheckQuery');
      form.value.content = response.data.config ? JSON.parse(response.data.config) : '';
      form.value.createTime = response.data.createTime ? response.data.createTime : '';
      form.value.updateTime = response.data.updateTime ? response.data.updateTime : '';
    });
  }
  function handleDeviceGroup() {
    TwoTitle.value = '选择设备分组';
    columns.value = [
      {
        prop: 'name',
        label: '分组',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'userName',
        label: '所属',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
    ];
    getSelectTypeList({
      type: 'deviceGroup',
      project: project.value,
      selectDate: form.value.selectDate
    }).then(response => {
      if (response.length) {
        response.forEach(element => {
          if (element.deviceIdList && element.deviceIdList.length) {
            element.deviceIdString = element.deviceIdList.map(item => {
              return {
                id: item.id,
                name: item.name
              };
            });
          } else {
            element.deviceIdString = [];
          }
        });
      }
      // console.log(response, 'ABCDEFG-handleSelectProject');
      tableData.value = response || [];
      openTwo.value = true;
    });
  }
  function handleDevice() {
    TwoTitle.value = '选择设备';
    columns.value = [
      {
        prop: 'id',
        label: '设备ID',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'name',
        label: '设备',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
      {
        prop: 'userName',
        label: '所属',
        minWidth: 150,
        align: 'center',
        showOverflowTooltip: true,
      },
    ];
    getSelectTypeList({
      type: 'project',
      project: project.value,
      selectDate: form.value.selectDate
    }).then(response => {
      tableData.value = response.deviceIdList || [];
      // console.log(response, 'handleDevice');
      if (response.length) {
        response.forEach(element => {
          if (element.name == project.value) {
            tableData.value = element.deviceIdList;
          }
          // console.log(response, 'handleDevice');
        });
      }
      openTwo.value = true;
    });
  }
  function cancelTwo() {
    columns.value = [];
    tableData.value = [];
    selectName.value = '';
    openTwo.value = false;
  }
  function openDialog(row) {
    // console.log(row, 'ABCDEFG-row');
    // form.value.deviceAction = row.deviceAction || '';
    project.value = row.project || '';
    form.value.selectDate = row.selectDate || '';
    form.value.userId = row.userId || '';
    open.value = true;
    // reset();
  }
  // 取消按钮
  function cancel() {
    proxy.resetForm("actionDialog");
    form.value.deviceName = '';
    form.value.createTime = '';
    form.value.updateTime = '';
    emit("cancel", false);
    open.value = false;
    // reset();
  }
  function findLabel(dict, dictValue) {
    let dictItem = dict.find(item => item.value == dictValue);
    return dictItem ? dictItem.label : '';
  }
  /** 提交按钮 */
  function submitForm() {
    // console.log(form.value, 'ABCDEFG-submitForm');
    proxy.$refs["actionDialog"].validate(valid => {
      if (valid) {
        buttonLoading.value = true;
        let params = [];
        getDevicesActionMessage({ deviceIdList: form.value.device.split(',') }).then(response => {
          let selectList = response.data || [];
          if (selectList.length) {
            let paramsList = selectList.map(item => {
              return {
                config: item.config,
                deviceId: item.deviceId,
              };
            });
            if (paramsList.length) {
              paramsList.forEach((item) => {
                item.config = JSON.stringify(form.value.content);
              });
              // console.log(paramsList, 'ABCDEFG-paramsList-end');
              updateDevices(paramsList).then(response => {
                buttonLoading.value = false;
                cancel();
                proxy.$modal.msgSuccess("发送成功");
              }).catch(e => {
                buttonLoading.value = false;
              });
            }
          }
        }).catch(e => {
        });

        // params.actionMessage = JSON.stringify(params.actionMessage);
        // console.log(params, 'ABCDEFG-params');


      }
    });
  }
  function handleSelectionChange(selection) {
    // console.log(selection, 'ABCDEFG-selection');
    // selection.value
    if (TwoTitle.value != '选择设备') {
      let ids = selection.map(item => item.deviceIdString);
      let mergedArray = [];
      if (ids.length) {
        ids.forEach(item => {
          mergedArray = [...mergedArray, ...item];
        });
      }
      // console.log(mergedArray, 'ABCDEFG-mergedArray');

      selectData.value = mergedArray.length ? mergedArray : [];
    } else {
      let idList = selection.map(item => {
        return {
          id: item.id,
          name: item.name,
        };
      });
      // console.log(idList, 'ABCDEFG-123');
      selectData.value = idList.length ? idList : [];
    }

  }
  defineExpose({
    openDialog
  });
</script>
<style lang="scss" scoped>
  :deep(.modal-wrap) {
    pointer-events: none !important;
    margin-top: 50%;
  }

  :deep() {
    .dialog-wrap {
      pointer-events: auto !important;
      margin-top: 15vh !important;
    }

    .dialog-wrap2 {
      margin-top: 20vh !important;
    }
  }

  :deep() {
    .el-dialog {
      /* pointer-events: auto !important; */
      display: flex;
      flex-direction: column;
      margin: 0 !important;
      position: absolute;
      top: 40%;
      left: 50%;
      transform: translate(-50%, -40%);
      max-height: calc(100% - 60px);
      max-width: calc(100% - 30px);
    }

    .el-dialog .el-dialog__body {
      flex: 1;
      overflow: auto;
    }
  }

  .iframeBg {
    background-image: url('../../../assets/images/samsung2.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    position: relative;
  }
</style>
